package com.srwl.mytx.widget;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.srwl.mytx.Constant;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.R;
import com.srwl.mytx.activity.ChatActivity;
import com.srwl.mytx.activity.LoginActivity;
import com.srwl.mytx.activity.TopicDetailsActivity;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.utils.ClickUtil;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.Utils;

import org.greenrobot.greendao.annotation.NotNull;

import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class CommentBottomBar extends RelativeLayout implements View.OnClickListener, OfferDialogV1.InteractionListener {
    private static final String TAG = "CommentBottomBar";
    @BindView(R.id.bottom_bar_background)
    FrameLayout bottomBarBackground;
    @BindView(R.id.rl_primary)
    View rl_primary;
    @BindView(R.id.rl_comment)
    View rl_comment;
    @BindView(R.id.iv_icon)
    ImageView iv_icon;
    @BindView(R.id.tv_author)
    TextView tv_authorName;
    @BindView(R.id.btn_comment)
    Button btn_comment;
    @BindView(R.id.et_content)
    public EditText et_content;
    @BindView(R.id.btn_commit)
    Button btn_commit;
    @BindView(R.id.btn_praise)
    ImageView btn_like;
    @BindView(R.id.tv_comment_size)
    TextView tv_commentSize;
    @BindView(R.id.tv_praise_size)
    TextView tv_likeSize;
    @BindView(R.id.iv_auction)
    ImageView iv_auction;
    private User manager;


    private InteractionListener listener;
    private int commentSize;
    private int praiseSize;
    private Topic topic;
    private boolean hadPraise;
    private long lastClickTime;
    private Context context;

    public CommentBottomBar(Context context) {
        super(context);
        this.context = context;
        inflate(context, R.layout.comment_bottom_bar, this);
        ButterKnife.bind(this);
    }

    public CommentBottomBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        inflate(context, R.layout.comment_bottom_bar, this);
        ButterKnife.bind(this);
    }

    public void init(Topic topic, int commentSize, int praiseSize, @NotNull InteractionListener listener) {
        this.topic = topic;
        this.commentSize = commentSize;
        this.praiseSize = praiseSize;
        this.listener = listener;

        showCommentInfo();
        manager = topic.getManager();
        showManagerInfo();
        // iv_icon.setOnClickListener(this);
        btn_comment.setOnClickListener(this);
        btn_commit.setOnClickListener(this);
        btn_like.setOnClickListener(this);
        Integer type = topic.getType();
        if (type == Constant.TOPIC_TYPE_AUCTION) {
            iv_auction.setVisibility(VISIBLE);
            iv_auction.setOnClickListener(this);
        }

        changeLikeImage(topic.getHadPraise());
        setPraiseSize(topic.getPraiseSize() == null ? 0 : topic.getPraiseSize());
    }

    public void init(int commentSize, int praiseSize, boolean hadPraise, User manager, @NotNull InteractionListener listener) {
        this.commentSize = commentSize;
        this.praiseSize = praiseSize;
        this.hadPraise = hadPraise;
        this.listener = listener;

        changeLikeImage(hadPraise);
        setPraiseSize(praiseSize);
        showCommentInfo();
        this.manager = manager;
        // showManagerInfo();
        if (manager != null) {
            // Glide.with(this).load(author.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_icon);
            GlideLoadUtils.glideLoad(context, manager.getAvatar(), iv_icon);
            if (TextUtils.isEmpty(manager.getUsername())) {
                tv_authorName.setText(manager.getNick());
            } else {
                tv_authorName.setText(manager.getUsername());
            }
        } else {
            iv_icon.setVisibility(INVISIBLE);
            tv_authorName.setVisibility(INVISIBLE);
        }
        // iv_icon.setOnClickListener(this);
        btn_comment.setOnClickListener(this);
        btn_commit.setOnClickListener(this);
        btn_like.setOnClickListener(this);
        if (topic == null) {
            return;
        }
        Integer type = topic.getType();
        if (type == Constant.TOPIC_TYPE_AUCTION) {
            iv_auction.setVisibility(VISIBLE);
            iv_auction.setOnClickListener(this);
        }
    }

    private void showManagerInfo() {
        if (manager == null) {
            iv_icon.setVisibility(GONE);
            tv_authorName.setText("管理者空缺中");
        } else {

            if (!iv_icon.isShown()) {//必须检查是否可见，因为可能被隐藏了
                iv_icon.setVisibility(VISIBLE);
            }
            //Glide.with(this).load(manager.getAvatar()).diskCacheStrategy(DiskCacheStrategy.ALL).into(iv_icon);
            GlideLoadUtils.glideLoad(context, manager.getAvatar(), iv_icon);
            if (!TextUtils.isEmpty(manager.getUsername())) {
                tv_authorName.setText(manager.getUsername());
            } else {
                tv_authorName.setText(manager.getNick());
            }
        }


    }

    public void onManagerGiveUp() {
        iv_icon.setVisibility(GONE);
        tv_authorName.setText("管理员空缺中");
        manager = null;
        topic.setManager(null);
    }

    /**
     * 申请成为管理员后，把自己的用户信息作为管理员信息显示出来
     */
    public void onApplyManagerSuccess() {
        manager = UserProfileManager.getInstance().getLoginUserInfo();
        topic.setManager(manager);
        showManagerInfo();
    }

    @OnClick(R.id.rl_user_info)
    public void onUserInfoClick() {

        if (manager == null && context instanceof TopicDetailsActivity) {

            ConfirmDialog dialog = new ConfirmDialog(context, "提示", "申请成为管理员", true);
            dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                @Override
                public void confirm() {
                    if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                        getContext().startActivity(new Intent(getContext(), LoginActivity.class).putExtra("EXTRA_CONTENT", "申请成为管理员需要先登录"));
                        return;
                    }
                    if (listener != null) {
                        listener.onApplyForManager();
                    }
                }
            });
            dialog.show();

            return;
        }

        if (manager != null) {

            UserDetailsDialog userDetailsDialog = new UserDetailsDialog(context, manager);
            userDetailsDialog.setUserDetailsDialogListener(new UserDetailsDialog.UserDetailsDialogListener() {
                @Override
                public void onMentionClick(String username) {

                }

                @Override
                public void onMessageClick(User user) {

                    context.startActivity(new Intent(getContext(), ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, user));
                }
            });
            userDetailsDialog.show();
        }

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
//            case R.id.iv_icon:
//                String loginUserID = UserProfileManager.getInstance().getLoginUserInfo().getuId();
//                if(topic.getManager()==null||TextUtils.equals(loginUserID,topic.getManager().getuId())){
//                    //为空的时候和登录用户是管理员的时候不能跳转到聊天页面
//                    return;
//                }
//                User userInfo = topic.getManager();
//                getContext().startActivity(new Intent(getContext(), ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, userInfo));
//                break;
            case R.id.btn_commit:
                if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                    getContext().startActivity(new Intent(getContext(), LoginActivity.class).putExtra("EXTRA_CONTENT", "评论需要先登录"));
                    return;
                }
                String content = et_content.getText().toString();
                if (TextUtils.isEmpty(content)) {
                    return;
                }
                btn_commit.setEnabled(false);
                if (listener != null) {
                    listener.onCommit(content);
                }
                break;
            case R.id.btn_comment:
                et_content.setHint("说点什么");
                if (listener != null) {
                    listener.onPrepareComment();
                }
                //让rl_comment 移动到屏幕下面的不可见区域
                rl_comment.setTranslationY(getHeight());
                rl_comment.setVisibility(View.VISIBLE);
                // displayCommentEditView();
                break;

            case R.id.btn_praise:
                if (Utils.isTempUser(UserProfileManager.getInstance().getLoginUserInfo())) {
                    getContext().startActivity(new Intent(getContext(), LoginActivity.class).putExtra("EXTRA_CONTENT", "点亮小红心需要先登录"));
                    return;
                }
                if (ClickUtil.isFastClick()) return;
                //如果已经 点过赞，就取消赞，
                if (hadPraise) {
                    removeTopicPraise();
                } else {
                    // periscopeLayout.addHeart(); 显示很多桃心
                    addTopicPraise();
                }
                break;
            case R.id.iv_auction:
                OfferDialogV1 offerDialog = new OfferDialogV1(getContext(), topic, this);
                offerDialog.show();
                break;

        }

    }


    public void scrollBackground(int scrollY) {
        bottomBarBackground.scrollTo(0, scrollY);
    }

    /**
     * 展示评论 点赞数量
     */
    private void showCommentInfo() {

        if (commentSize != 0) {
            tv_commentSize.setVisibility(View.VISIBLE);
            tv_commentSize.setText(Utils.numberFormat(commentSize));
        }
        if (praiseSize != 0) {
            tv_likeSize.setVisibility(View.VISIBLE);
            tv_likeSize.setText(Utils.numberFormat(praiseSize));
        }
    }


    public void showHint(String hint) {
        et_content.setText("");
        et_content.setHint(hint);

        displayCommentEditView();
    }

    public void showHintNotClearContent(String hint) {

        et_content.setHint(hint);
        displayCommentEditView();
    }

    public void showSoftKeyBord() {
        et_content.setFocusable(true);
        et_content.setFocusableInTouchMode(true);
        et_content.requestFocus();
        InputMethodManager inputManager =
                (InputMethodManager) et_content.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(et_content, 0);
    }

    /**
     * 展示评论编辑视图
     */
    public void displayCommentEditView() {

        rl_comment.setVisibility(View.VISIBLE);
        rl_comment.setTranslationY(0);
    }


    public void setCommentLayoutTranslationY(float translationY) {
        int height = getHeight();
        if (translationY < height) {
            rl_comment.setTranslationY(height - translationY);
        } else {
            rl_comment.setTranslationY(0);
        }
    }

    /**
     * 评论提交完成
     */
    public void commitComplete() {
        updateTopicData();
        //  hideCommentEditView();
        clearEditView();
        setCommitButton(true);
    }


    public void setCommitButton(boolean isEnable) {
        btn_commit.setEnabled(isEnable);
    }


    public void clearEditView() {
        et_content.setText("");
    }

    /**
     * 隐藏评论编辑视图
     */
    public void hideCommentEditView() {
        if (!rl_primary.isShown()) {
            rl_primary.setVisibility(View.VISIBLE);
            rl_comment.setVisibility(View.GONE);
        }
    }

    public void updateTopicData() {
        commentSize++;
        if (topic != null) {
            topic.setCommentSize(commentSize);
            topic.setUpdated(new Date());
        }
        if (tv_commentSize.getVisibility() == View.INVISIBLE) {
            tv_commentSize.setVisibility(View.VISIBLE);
        }
        tv_commentSize.setText(Utils.numberFormat(commentSize));
    }

    /**
     * 点赞
     */
    private void addTopicPraise() {
        /*if (topic == null) {
            return;
        }*/
        //点赞数量 加1，
        praiseSize++;
        if (topic != null) {
            topic.setPraiseSize(praiseSize);
            topic.setHadPraise(true);
        }
        if (tv_likeSize.getVisibility() == View.INVISIBLE) {
            tv_likeSize.setVisibility(View.VISIBLE);
        }
        tv_likeSize.setText(Utils.numberFormat(praiseSize));
        changeLikeImage(true);
        if (listener != null) {
            listener.onAddPraise();
        }
    }

    /**
     * 取消点赞
     */
    private void removeTopicPraise() {
        /*if (topic == null) {
            return;
        }*/
        //点赞数量 减去 1，
        praiseSize--;
        if (topic != null) {
            topic.setPraiseSize(praiseSize);
            topic.setHadPraise(false);
        }
        if (praiseSize == 0) {
            tv_likeSize.setVisibility(INVISIBLE);
        } else {
            tv_likeSize.setText(Utils.numberFormat2(praiseSize));
        }

        changeLikeImage(false);
        if (listener != null) {
            listener.onRemovePraise();
        }
    }

    public void setPraiseSize(int praiseSize) {
        this.praiseSize = praiseSize;
        if (praiseSize == 0) {
            tv_likeSize.setVisibility(INVISIBLE);
        } else {
            tv_likeSize.setText(Utils.numberFormat(praiseSize));
        }

    }

    public void changeLikeImage(boolean hadPraise) {
        this.hadPraise = hadPraise;
        if (hadPraise) {
            btn_like.setBackground(getResources().getDrawable(R.drawable.tx_like_red_3));

        } else {
            btn_like.setBackground(getResources().getDrawable(R.drawable.tx_like_5));

        }

    }


    public void setListener(InteractionListener listener) {
        this.listener = listener;
    }

    @Override
    public void onOfferSuccess(double amount) {

    }

    public interface InteractionListener {

        void onCommit(String content);

        void onAddPraise();

        void onRemovePraise();

        /**
         * 准备回复主题的时候
         */
        void onPrepareComment();

        void onApplyForManager();
    }
}
